package com.tgy.MyFlowable.workflow.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctsi.core.common.api.Result;
import com.ctsi.core.common.util.$;
import com.ctsi.core.common.util.PastTimeFormatUtil;
import com.ctsi.core.common.util.StringPool;
import com.ctsi.core.database.util.PageUtil;
import com.ctsi.system.service.IUserService;
import com.ctsi.workflow.dto.FlwInstanceTaskDTO;
import com.ctsi.workflow.service.IFlwInstanceTaskService;
import com.ctsi.workflow.vo.FlwInstanceTaskVO;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.HistoryService;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 实例任务业务接口实现类
 *
 * @version 1.0
 * @author: wang xiao xiang
 * @date: 2021/8/8 19:42
 */
@Service
@RequiredArgsConstructor
public class FlwInstanceTaskServiceImpl implements IFlwInstanceTaskService {

    private final HistoryService historyService;

    @Autowired
    private IUserService userService;

    @Override
    public IPage<FlwInstanceTaskVO> page(FlwInstanceTaskDTO flwInstanceTaskDTO) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        if ($.isNotNull(flwInstanceTaskDTO)) {
            if ($.isNotEmpty(flwInstanceTaskDTO.getProcessInstanceId())) {
                //根据实例查询
                historicTaskInstanceQuery.processInstanceId(flwInstanceTaskDTO.getProcessInstanceId());
            }

            if ($.isNotEmpty(flwInstanceTaskDTO.getName())) {
                //根据任务名称模糊查询
                historicTaskInstanceQuery.taskNameLike(StringPool.PERCENT + flwInstanceTaskDTO.getName() + StringPool.PERCENT);
            }

            if ($.isNotEmpty(flwInstanceTaskDTO.getFinished())) {
                //根据是否结束查询
                if (flwInstanceTaskDTO.getFinished()) {
                    historicTaskInstanceQuery.finished();
                } else {
                    historicTaskInstanceQuery.unfinished();
                }
            }
        }
        //根据任务创建时间倒序，最新创建的任务在最上面
        historicTaskInstanceQuery.orderByHistoricTaskInstanceStartTime().desc();
        Page<FlwInstanceTaskVO> defaultPage = PageUtil.getPage(flwInstanceTaskDTO);
        long current = defaultPage.getCurrent();
        long size = defaultPage.getSize();
        List<HistoricTaskInstance> taskList = historicTaskInstanceQuery
                .listPage(Convert.toInt((current - 1) * size), Convert.toInt(size));
        defaultPage.setTotal(historicTaskInstanceQuery.count());
        // 转换为自定义的FlwInstanceTaskVO对象
        List<FlwInstanceTaskVO> collect = taskList.stream().map(historicTaskInstance -> convertToInstanceTaskVO(historicTaskInstance)).collect(Collectors.toList());
        defaultPage.setRecords(collect);
        return defaultPage;
    }

    /**
     * 将单个实例任务结果转换为自定义结果
     *
     * @param historicTaskInstance 历史任务实现
     * @return
     */
    private FlwInstanceTaskVO convertToInstanceTaskVO(HistoricTaskInstance historicTaskInstance) {
        FlwInstanceTaskVO flwInstanceTaskVO = $.copy(historicTaskInstance, FlwInstanceTaskVO.class);
        flwInstanceTaskVO.setActivityId(historicTaskInstance.getTaskDefinitionKey());
        if ($.isNotEmpty(historicTaskInstance.getAssignee())) {
            flwInstanceTaskVO.setAssigneeName(Result.data(userService.getById($.toLong(historicTaskInstance.getAssignee()))).getData().getAccount());
            flwInstanceTaskVO.setAssigneeInfo("处理人:" + flwInstanceTaskVO.getAssigneeName());
        } else {
            flwInstanceTaskVO.setAssigneeName(Result.data(userService.getById($.toLong(historicTaskInstance.getId()))).getData().getAccount());
            flwInstanceTaskVO.setAssigneeInfo("处理人:" + flwInstanceTaskVO.getAssigneeName());
        }
        flwInstanceTaskVO.setFormatCreateTime($.formatPastTime(historicTaskInstance.getCreateTime()));
        if ($.isNotEmpty(historicTaskInstance.getEndTime())) {
            flwInstanceTaskVO.setFormatEndTime(PastTimeFormatUtil.formatPastTime(historicTaskInstance.getEndTime()));
            flwInstanceTaskVO.setEnded(true);
        } else {
            flwInstanceTaskVO.setEnded(false);
        }
        if ($.isNotEmpty(historicTaskInstance.getDurationInMillis())) {
            flwInstanceTaskVO.setDuration(DateUtil.formatBetween(historicTaskInstance.getDurationInMillis(), BetweenFormater.Level.SECOND));
        }
        return flwInstanceTaskVO;
    }
}

